<template>
  <!--用户添加&修改-->
  <div class="search">
    <f-form ref="form" :action="api.managerUser" :form-key="this.formItem.userId">
      <f-form-item label="所属机构" type="select" name="organizationId" :value="formItem.organizationId" :data="api.organization.list" valueKey="organizationId" label-key="organizationName" :required="true" v-if="this.superAdmin"/>
      <f-form-item label="账户名" name="userName" :required="true" :rules="rules.userName" :value="formItem.userName"/>
      <f-form-item label="昵称" name="nickName" :required="true" :value="formItem.nickName"/>
      <f-form-item label="密码" name="password" :required="true" :rules="rules.required(6,10)" :validator="validateToNextPassword" v-if="isAdd" :value.sync="formItem.password"/>
      <f-form-item label="确认密码" name="passwordConfirm" :required="true" :rules="rules.required(6,10)" :validator="compareToFirstPassword" v-if="isAdd" :value.sync="formItem.passwordConfirm"/>
      <f-form-item label="手机号" name="mobile" :value="formItem.mobile"/>
      <f-form-item label="邮箱" name="email" :value="formItem.email"/>
      <f-form-item label="状态" name="status" type="radio" v-if="loaded" :radio-button="true" :data="api.managerUser.userStatus" :value="formItem.status"/>
      <f-form-item label="描述" name="userDesc" type="textarea" :value="formItem.userDesc"/>
    </f-form>
  </div>
</template>

<script>
  export default {
    name: 'userForm',
    props: {},
    data() {
      return {
        isAdd: false,
        loaded: false,
        handlerName: '',
        formItem: this.getFormItem()
      }
    },
    methods: {
      compareToFirstPassword(rule, value, callback) {
        if (value && value.length >= 6 && value !== this.formItem.password) {
          callback('2次密码不一致')
        } else {
          callback()
        }
      },
      validateToNextPassword(rule, value, callback) {
        const form = this.$refs.form.getForm()
        if (value) {
          form.validateFields(['passwordConfirm'], { force: 'change' })
        }
        callback()
      },
      getFormItem() {
        return {
          userId: '',
          userName: '',
          nickName: '',
          password: '',
          organizationId: null,
          passwordConfirm: '',
          status: 1,
          companyId: '',
          email: '',
          mobile: '',
          userType: 'normal',
          userDesc: '',
          avatar: ''
        }
      },
      setData(data) {
        this.$refs.form.resetFields()
        this.formItem = this.getFormItem()
        if (data && data.userId) {
          this.formItem = data
        } else {
          this.isAdd = true
        }
        this.loaded = true
      },
      handleSubmit(callback) {
        let params = {}
        if (this.isAdd) {
          params.handlerName = 'adminUserAddHandler'
        }
        this.$refs.form.submit(params, callback)
      }
    }
  }
</script>

<style scoped lang="less" rel="stylesheet/less">

</style>
